package com.ehouse.provider;

import android.content.ContentProvider;
import android.content.ContentUris;
import android.content.ContentValues;
import android.content.Context;
import android.content.UriMatcher;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteQueryBuilder;
import android.net.Uri;
import android.text.TextUtils;

import com.ehouse.database.DatabaseHelper;
import com.ehouse.database.IrrigationScheduleTable;
import com.ehouse.database.IrrigationTable;
import com.ehouse.database.LightScheduleTable;
import com.ehouse.database.LightTable;
import com.ehouse.database.TemperatureScheduleTable;
import com.ehouse.database.TemperatureTable;
import com.ehouse.database.WindowTable;

public class MainContentProvider extends ContentProvider {

  public static final Uri BASE_URI = 
      Uri.parse("content://com.ehouse.provider/");
  
  DatabaseHelper dbHelper;

  @Override
  public boolean onCreate() {
    Context context = getContext();

    dbHelper = new DatabaseHelper(context,
    		DatabaseHelper.DATABASE_NAME, null,
    		DatabaseHelper.DATABASE_VERSION);

    return true;
  }
  

  //Create the constants used to differentiate between the different URI
  //requests.
  private static final int SWITCHES = 1;
  private static final int SWITCH_ID = 2;
  private static final int TEMPERATURES = 3;
  private static final int TEMPERATURE_ID = 4;
  private static final int IRRIGATIONS = 5;
  private static final int IRRIGATION_ID = 6;
  private static final int WINDOWS = 7;
  private static final int WINDOW_ID = 8;
  
  private static final int SWITCHES_S = 9;
  private static final int SWITCH_S_ID = 10;
  private static final int TEMPERATURES_S = 11;
  private static final int TEMPERATURE_S_ID = 12;
  private static final int IRRIGATIONS_S = 13;
  private static final int IRRIGATION_S_ID = 14;
  

  private static final UriMatcher uriMatcher;

  //Allocate the UriMatcher object, where a URI ending in 'earthquakes' will
  //correspond to a request for all earthquakes, and 'earthquakes' with a
  //trailing '/[rowID]' will represent a single earthquake row.
  static {
   uriMatcher = new UriMatcher(UriMatcher.NO_MATCH);
   uriMatcher.addURI("com.ehouse.provider", LightTable.NAME, SWITCHES);
   uriMatcher.addURI("com.ehouse.provider", LightTable.NAME+"/#", SWITCH_ID);
   uriMatcher.addURI("com.ehouse.provider", TemperatureTable.NAME, TEMPERATURES);
   uriMatcher.addURI("com.ehouse.provider", TemperatureTable.NAME +"/#", TEMPERATURE_ID);
   uriMatcher.addURI("com.ehouse.provider", IrrigationTable.NAME, IRRIGATIONS);
   uriMatcher.addURI("com.ehouse.provider", IrrigationTable.NAME + "/#", IRRIGATION_ID);
   uriMatcher.addURI("com.ehouse.provider", WindowTable.NAME, WINDOWS);
   uriMatcher.addURI("com.ehouse.provider", WindowTable.NAME + "/#", WINDOW_ID);
   
   uriMatcher.addURI("com.ehouse.provider", LightScheduleTable.NAME, SWITCHES_S);
   uriMatcher.addURI("com.ehouse.provider", LightScheduleTable.NAME+"/#", SWITCH_S_ID);
   uriMatcher.addURI("com.ehouse.provider", TemperatureScheduleTable.NAME, TEMPERATURES_S);
   uriMatcher.addURI("com.ehouse.provider", TemperatureScheduleTable.NAME +"/#", TEMPERATURE_S_ID);
   uriMatcher.addURI("com.ehouse.provider", IrrigationScheduleTable.NAME, IRRIGATIONS_S);
   uriMatcher.addURI("com.ehouse.provider", IrrigationScheduleTable.NAME + "/#", IRRIGATION_S_ID);
   
  }
  
  @Override
  public String getType(Uri uri) {
    switch (uriMatcher.match(uri)) {
      case SWITCHES  : return "vnd.android.cursor.dir/com.ehouse.provider";
      case SWITCH_ID: return "vnd.android.cursor.item/com.ehouse.provider";

      case TEMPERATURES  : return "vnd.android.cursor.dir/com.ehouse.provider";
      case TEMPERATURE_ID: return "vnd.android.cursor.item/com.ehouse.provider";

      case IRRIGATIONS  : return "vnd.android.cursor.dir/com.ehouse.provider";
      case IRRIGATION_ID: return "vnd.android.cursor.item/com.ehouse.provider";

      case WINDOWS  : return "vnd.android.cursor.dir/com.ehouse.provider";
      case WINDOW_ID: return "vnd.android.cursor.item/com.ehouse.provider";
      
      case SWITCHES_S  : return "vnd.android.cursor.dir/com.ehouse.provider";
      case SWITCH_S_ID: return "vnd.android.cursor.item/com.ehouse.provider";

      case TEMPERATURES_S  : return "vnd.android.cursor.dir/com.ehouse.provider";
      case TEMPERATURE_S_ID: return "vnd.android.cursor.item/com.ehouse.provider";

      case IRRIGATIONS_S  : return "vnd.android.cursor.dir/com.ehouse.provider";
      case IRRIGATION_S_ID: return "vnd.android.cursor.item/com.ehouse.provider";
      
      default: throw new IllegalArgumentException("Unsupported URI: " + uri);
    }
  }


  @Override
  public Cursor query(Uri uri,
                      String[] projection,
                      String selection,
                      String[] selectionArgs,
                      String sort) {

    SQLiteDatabase database = dbHelper.getWritableDatabase();

    SQLiteQueryBuilder qb = new SQLiteQueryBuilder();

   
 // If this is a row query, limit the result set to the passed in row.
    switch (uriMatcher.match(uri)) {
      case SWITCHES: qb.setTables(LightTable.NAME);
      break;
      case SWITCH_ID:  qb.setTables(LightTable.NAME);
      break;
      case TEMPERATURES  : qb.setTables(TemperatureTable.NAME);
      break;
      case TEMPERATURE_ID: qb.setTables(TemperatureTable.NAME);
      break;
      case IRRIGATIONS  : qb.setTables(IrrigationTable.NAME);
      break;
      case IRRIGATION_ID: qb.setTables(IrrigationTable.NAME);
      break;
      case WINDOWS  : qb.setTables(WindowTable.NAME);
      break;
      case WINDOW_ID: qb.setTables(WindowTable.NAME);
      break;
      case SWITCHES_S: qb.setTables(LightScheduleTable.NAME);
      break;
      case SWITCH_S_ID:  qb.setTables(LightScheduleTable.NAME);
      break;
      case TEMPERATURES_S  : qb.setTables(TemperatureScheduleTable.NAME);
      break;
      case TEMPERATURE_S_ID: qb.setTables(TemperatureScheduleTable.NAME);
      break;
      case IRRIGATIONS_S  : qb.setTables(IrrigationScheduleTable.NAME);
      break;
      case IRRIGATION_S_ID: qb.setTables(TemperatureScheduleTable.NAME);
      break;
      default      : break;
    }
    // If this is a row query, limit the result set to the passed in row.
    switch (uriMatcher.match(uri)) {
    	case SWITCH_ID: qb.appendWhere(LightTable.COLUMN_ID + "=" + uri.getPathSegments().get(1));
    	 break;
    	case TEMPERATURE_ID: qb.appendWhere(TemperatureTable.COLUMN_ID + "=" + uri.getPathSegments().get(1));
    	 break;
    	case IRRIGATION_ID: qb.appendWhere(IrrigationTable.COLUMN_ID + "=" + uri.getPathSegments().get(1));
    	 break;
    	case SWITCH_S_ID: qb.appendWhere(LightScheduleTable.COLUMN_ID + "=" + uri.getPathSegments().get(1));
	   	 break;
	   	case TEMPERATURE_S_ID: qb.appendWhere(TemperatureScheduleTable.COLUMN_ID + "=" + uri.getPathSegments().get(1));
	   	 break;
	   	case IRRIGATION_S_ID: qb.appendWhere(IrrigationScheduleTable.COLUMN_ID + "=" + uri.getPathSegments().get(1));
	   	 break;
    	case WINDOW_ID: qb.appendWhere(WindowTable.COLUMN_ID + "=" + uri.getPathSegments().get(1));
      default      : break;
    }

    // If no sort order is specified, sort by date / time
    String orderBy;
    if (TextUtils.isEmpty(sort)) {
      orderBy = "_id";
    } else {
      orderBy = sort;
    }

    // Apply the query to the underlying database.
    Cursor c = qb.query(database,
                        projection,
                        selection, selectionArgs,
                        null, null,
                        orderBy);
    // Register the contexts ContentResolver to be notified if
    // the cursor result set changes.
    c.setNotificationUri(getContext().getContentResolver(), uri);

    // Return a cursor to the query result.
    return c;
  }

  @Override
  public Uri insert(Uri _uri, ContentValues _initialValues) {
    SQLiteDatabase database = dbHelper.getWritableDatabase();
    
    // Insert the new row. The call to database.insert will return the row number
    // if it is successful.
    long rowID = 0;
    switch (uriMatcher.match(_uri)) {
	    case SWITCHES: {
	    	rowID = database.insert(
	        		LightTable.NAME, "switch", _initialValues);
	    	if (rowID > 0) {
		          Uri uri = ContentUris.withAppendedId(LightTable.CONTENT_URI, rowID);
		          getContext().getContentResolver().notifyChange(uri, null);
		          return uri;
		        }
	    	break;
	    }
	    case TEMPERATURES  :{
	    	rowID = database.insert(
	        		TemperatureTable.NAME, "temperature", _initialValues);
	    	if (rowID > 0) {
		          Uri uri = ContentUris.withAppendedId(TemperatureTable.CONTENT_URI, rowID);
		          getContext().getContentResolver().notifyChange(uri, null);
		          return uri;
		        }
	    	break;
	    }
	
	    case IRRIGATIONS  : {
	    	rowID = database.insert(
	        		IrrigationTable.NAME, "irrigation", _initialValues);
	    	if (rowID > 0) {
		          Uri uri = ContentUris.withAppendedId(IrrigationTable.CONTENT_URI, rowID);
		          getContext().getContentResolver().notifyChange(uri, null);
		          return uri;
		        }
	    	break;
	    }
	    
	    case SWITCHES_S: {
	    	rowID = database.insert(
	        		LightScheduleTable.NAME, "switch_schedule", _initialValues);
	    	if (rowID > 0) {
		          Uri uri = ContentUris.withAppendedId(LightScheduleTable.CONTENT_URI, rowID);
		          getContext().getContentResolver().notifyChange(uri, null);
		          return uri;
		        }
	    	break;
	    }
	    case TEMPERATURES_S  :{
	    	rowID = database.insert(
	        		TemperatureScheduleTable.NAME, "temperature_schedule", _initialValues);
	    	if (rowID > 0) {
		          Uri uri = ContentUris.withAppendedId(TemperatureScheduleTable.CONTENT_URI, rowID);
		          getContext().getContentResolver().notifyChange(uri, null);
		          return uri;
		        }
	    	break;
	    }
	
	    case IRRIGATIONS_S  : {
	    	rowID = database.insert(
	        		IrrigationScheduleTable.NAME, "irrigtaion_schedule", _initialValues);
	    	if (rowID > 0) {
		          Uri uri = ContentUris.withAppendedId(IrrigationScheduleTable.CONTENT_URI, rowID);
		          getContext().getContentResolver().notifyChange(uri, null);
		          return uri;
		        }
	    	break;
	    }
	    
	
	    case WINDOWS  : {
	    	rowID = database.insert(
	        		WindowTable.NAME, "window", _initialValues);
	    	// Return a URI to the newly inserted row on success.
	        if (rowID > 0) {
	          Uri uri = ContentUris.withAppendedId(WindowTable.CONTENT_URI, rowID);
	          getContext().getContentResolver().notifyChange(uri, null);
	          return uri;
	        }
	        break;
	    }
	    default      : 
	        throw new SQLException("Failed to insert row into " + _uri);
	  }
	return _uri;
  }

  @Override
  public int delete(Uri uri, String where, String[] whereArgs) {
    SQLiteDatabase database = dbHelper.getWritableDatabase();
    String segment;
    int count;
    switch (uriMatcher.match(uri)) {
      case SWITCHES:
        count = database.delete(
        		LightTable.NAME, where, whereArgs);
        break;
      case SWITCH_ID:
        segment = uri.getPathSegments().get(1);
        count = database.delete(LightTable.NAME, 
                LightTable.COLUMN_ID + "=" 
                + segment
                + (!TextUtils.isEmpty(where) ? " AND ("
                + where + ')' : ""), whereArgs);
        break;
        
      case TEMPERATURES:
          count = database.delete(
          		TemperatureTable.NAME, where, whereArgs);
          break;
        case TEMPERATURE_ID:
          segment = uri.getPathSegments().get(1);
          count = database.delete(TemperatureTable.NAME, 
                  TemperatureTable.COLUMN_ID + "=" 
                  + segment
                  + (!TextUtils.isEmpty(where) ? " AND ("
                  + where + ')' : ""), whereArgs);
          break;
          
        case IRRIGATIONS:
            count = database.delete(
            		IrrigationTable.NAME, where, whereArgs);
            break;
          case IRRIGATION_ID:
            segment = uri.getPathSegments().get(1);
            count = database.delete(IrrigationTable.NAME, 
                    IrrigationTable.COLUMN_ID + "=" 
                    + segment
                    + (!TextUtils.isEmpty(where) ? " AND ("
                    + where + ')' : ""), whereArgs);
            break;
	      case SWITCHES_S:
	          count = database.delete(
	          		LightScheduleTable.NAME, where, whereArgs);
	          break;
	        case SWITCH_S_ID:
	          segment = uri.getPathSegments().get(1);
	          count = database.delete(LightScheduleTable.NAME, 
	                  LightScheduleTable.COLUMN_ID + "=" 
	                  + segment
	                  + (!TextUtils.isEmpty(where) ? " AND ("
	                  + where + ')' : ""), whereArgs);
	          break;
	          
	        case TEMPERATURES_S:
	            count = database.delete(
	            		TemperatureScheduleTable.NAME, where, whereArgs);
	            break;
	          case TEMPERATURE_S_ID:
	            segment = uri.getPathSegments().get(1);
	            count = database.delete(TemperatureScheduleTable.NAME, 
	                    TemperatureScheduleTable.COLUMN_ID + "=" 
	                    + segment
	                    + (!TextUtils.isEmpty(where) ? " AND ("
	                    + where + ')' : ""), whereArgs);
	            break;
	            
	          case IRRIGATIONS_S:
	              count = database.delete(
	              		IrrigationScheduleTable.NAME, where, whereArgs);
	              break;
	            case IRRIGATION_S_ID:
	              segment = uri.getPathSegments().get(1);
	              count = database.delete(IrrigationScheduleTable.NAME, 
	                      IrrigationScheduleTable.COLUMN_ID + "=" 
	                      + segment
	                      + (!TextUtils.isEmpty(where) ? " AND ("
	                      + where + ')' : ""), whereArgs);
	              break;
            
          case WINDOWS:
              count = database.delete(
              		WindowTable.NAME, where, whereArgs);
              break;
            case WINDOW_ID:
              segment = uri.getPathSegments().get(1);
              count = database.delete(WindowTable.NAME, 
            		  WindowTable.COLUMN_ID + "=" 
                      + segment
                      + (!TextUtils.isEmpty(where) ? " AND ("
                      + where + ')' : ""), whereArgs);
              break;

      default: throw new IllegalArgumentException("Unsupported URI: " + uri);
    }

    getContext().getContentResolver().notifyChange(uri, null);
    return count;
  }

  @Override
  public int update(Uri uri, ContentValues values, 
             String where, String[] whereArgs) {
    SQLiteDatabase database = dbHelper.getWritableDatabase();
    
    int count;
    String segment;
    switch (uriMatcher.match(uri)) {
      case SWITCHES: 
        count = database.update(LightTable.NAME, 
                                values, where, whereArgs);
        break;
      case SWITCH_ID: 
        segment = uri.getPathSegments().get(1);
        count = database.update(LightTable.NAME, 
                                values, LightTable.COLUMN_ID
                                  + "=" + segment
                                  + (!TextUtils.isEmpty(where) ? " AND ("
                                  + where + ')' : ""), whereArgs);
        break;
        
      case TEMPERATURES: 
          count = database.update(TemperatureTable.NAME, 
                                  values, where, whereArgs);
          break;
        case TEMPERATURE_ID: 
          segment = uri.getPathSegments().get(1);
          count = database.update(TemperatureTable.NAME, 
                                  values, TemperatureTable.COLUMN_ID
                                    + "=" + segment
                                    + (!TextUtils.isEmpty(where) ? " AND ("
                                    + where + ')' : ""), whereArgs);
          break;
          
        case IRRIGATIONS: 
            count = database.update(IrrigationTable.NAME, 
                                    values, where, whereArgs);
            break;
          case IRRIGATION_ID: 
            segment = uri.getPathSegments().get(1);
            count = database.update(IrrigationTable.NAME, 
                                    values, IrrigationTable.COLUMN_ID
                                      + "=" + segment
                                      + (!TextUtils.isEmpty(where) ? " AND ("
                                      + where + ')' : ""), whereArgs);
            break;
            
          case SWITCHES_S: 
              count = database.update(LightScheduleTable.NAME, 
                                      values, where, whereArgs);
              break;
            case SWITCH_S_ID: 
              segment = uri.getPathSegments().get(1);
              count = database.update(LightScheduleTable.NAME, 
                                      values, LightScheduleTable.COLUMN_ID
                                        + "=" + segment
                                        + (!TextUtils.isEmpty(where) ? " AND ("
                                        + where + ')' : ""), whereArgs);
              break;
              
            case TEMPERATURES_S: 
                count = database.update(TemperatureScheduleTable.NAME, 
                                        values, where, whereArgs);
                break;
              case TEMPERATURE_S_ID: 
                segment = uri.getPathSegments().get(1);
                count = database.update(TemperatureScheduleTable.NAME, 
                                        values, TemperatureScheduleTable.COLUMN_ID
                                          + "=" + segment
                                          + (!TextUtils.isEmpty(where) ? " AND ("
                                          + where + ')' : ""), whereArgs);
                break;
                
              case IRRIGATIONS_S: 
                  count = database.update(IrrigationScheduleTable.NAME, 
                                          values, where, whereArgs);
                  break;
                case IRRIGATION_S_ID: 
                  segment = uri.getPathSegments().get(1);
                  count = database.update(IrrigationScheduleTable.NAME, 
                                          values, IrrigationScheduleTable.COLUMN_ID
                                            + "=" + segment
                                            + (!TextUtils.isEmpty(where) ? " AND ("
                                            + where + ')' : ""), whereArgs);
                  break;
            
          case WINDOWS: 
              count = database.update(WindowTable.NAME, 
                                      values, where, whereArgs);
              break;
            case WINDOW_ID: 
              segment = uri.getPathSegments().get(1);
              count = database.update(WindowTable.NAME, 
                                      values, WindowTable.COLUMN_ID
                                        + "=" + segment
                                        + (!TextUtils.isEmpty(where) ? " AND ("
                                        + where + ')' : ""), whereArgs);
              break;
      default: throw new IllegalArgumentException("Unknown URI " + uri);
    }

    getContext().getContentResolver().notifyChange(uri, null);
    return count;
  }
 
}